<template>
  <el-dialog
    v-model="dialogVisible"
    title="角色分配"
    width="600px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div class="role-assignment">
      <div class="user-info">
        <el-avatar :size="40" :src="user?.avatar">
          <el-icon><UserFilled /></el-icon>
        </el-avatar>
        <div class="user-details">
          <div class="user-name">{{ user?.username }}</div>
          <div class="user-email">{{ user?.email }}</div>
        </div>
      </div>
      
      <el-divider content-position="left">角色配置</el-divider>
      
      <div v-loading="loading" class="roles-content">
        <div class="current-roles">
          <h4>当前角色</h4>
          <div class="role-tags">
            <el-tag 
              v-for="role in currentRoles" 
              :key="role.id"
              :type="getRoleTagType(role.code)"
              size="large"
              closable
              @close="removeRole(role.id)"
            >
              {{ role.name }}
            </el-tag>
            <el-tag v-if="currentRoles.length === 0" type="info">暂无角色</el-tag>
          </div>
        </div>
        
        <div class="available-roles">
          <h4>可分配角色</h4>
          <div class="role-list">
            <div 
              v-for="role in availableRoles" 
              :key="role.id"
              class="role-item"
              @click="addRole(role)"
            >
              <div class="role-icon">
                <el-icon><UserFilled /></el-icon>
              </div>
              <div class="role-info">
                <div class="role-name">{{ role.name }}</div>
                <div class="role-desc">{{ role.description }}</div>
              </div>
              <div class="role-action">
                <el-button type="primary" size="small" circle>
                  <el-icon><Plus /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { UserFilled, Plus } from '@element-plus/icons-vue'

const props = defineProps({
  visible: Boolean,
  user: Object
})

const emit = defineEmits(['update:visible', 'confirm'])

const loading = ref(false)
const submitLoading = ref(false)
const currentRoles = ref([])
const allRoles = ref([])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 可分配的角色（排除已有的）
const availableRoles = computed(() => {
  const currentRoleIds = currentRoles.value.map(role => role.id)
  return allRoles.value.filter(role => !currentRoleIds.includes(role.id))
})

// 加载真实角色数据
const loadAllRoles = async () => {
  try {
    const { roleApi } = await import('@/api/role')
    const response = await roleApi.getRoles()
    
    console.log('加载所有角色:', response)
    
    if (response.data && Array.isArray(response.data)) {
      allRoles.value = response.data.map(role => ({
        id: role.id,
        name: role.roleName, // 后端字段是roleName
        code: role.roleCode || role.roleName, // 后端字段是roleCode
        description: role.description || '暂无描述'
      }))
      console.log('角色数据加载成功:', allRoles.value)
    } else {
      console.warn('角色API返回格式异常:', response)
      allRoles.value = []
    }
  } catch (error) {
    console.error('加载角色数据失败:', error)
    ElMessage.error('加载角色数据失败')
    allRoles.value = []
  }
}

// 监听用户变化和对话框可见性，加载角色数据
watch(() => props.user, (newUser) => {
  if (newUser && props.visible) {
    loadRoles()
  }
}, { immediate: true })

// 监听对话框可见性
watch(() => props.visible, (visible) => {
  if (visible) {
    loadAllRoles() // 加载所有角色数据
    if (props.user) {
      loadRoles() // 加载用户当前角色
    }
  }
})

const loadRoles = async () => {
  try {
    loading.value = true
    
    // 使用真实API加载用户当前角色
    if (props.user?.id) {
      // 从用户对象中获取角色信息，并格式化为与allRoles一致的格式
      const userRoles = props.user?.roles || []
      currentRoles.value = userRoles.map(role => ({
        id: role.id,
        name: role.roleName || role.name, // 兼容不同的字段名
        code: role.roleCode || role.code || role.roleName || role.name,
        description: role.description || '暂无描述'
      }))
      console.log('加载用户角色:', currentRoles.value)
      console.log('原始用户角色数据:', userRoles)
    } else {
      currentRoles.value = []
    }
    
  } catch (error) {
    console.error('加载角色失败:', error)
    ElMessage.error('加载角色失败')
  } finally {
    loading.value = false
  }
}

const getRoleTagType = (code) => {
  const typeMap = {
    'super_admin': 'danger',
    'admin': 'warning',
    'user': 'primary',
    'guest': 'info',
    'editor': 'success'
  }
  return typeMap[code] || 'primary'
}

const addRole = (role) => {
  console.log('添加角色:', role)
  console.log('当前角色列表:', currentRoles.value)
  
  if (currentRoles.value.find(r => r.id === role.id)) {
    ElMessage.warning('该角色已存在')
    return
  }
  
  currentRoles.value.push({ ...role })
  console.log('添加后角色列表:', currentRoles.value)
  ElMessage.success(`已添加角色：${role.name}`)
}

const removeRole = (roleId) => {
  console.log('移除角色ID:', roleId)
  console.log('当前角色列表:', currentRoles.value)
  
  const index = currentRoles.value.findIndex(role => role.id === roleId)
  if (index > -1) {
    const removedRole = currentRoles.value.splice(index, 1)[0]
    console.log('移除后角色列表:', currentRoles.value)
    ElMessage.success(`已移除角色：${removedRole.name}`)
  }
}

const handleSubmit = async () => {
  try {
    submitLoading.value = true
    
    const roleIds = currentRoles.value.map(role => role.id)
    console.log('提交角色分配数据:', {
      userId: props.user.id,
      roleIds: roleIds,
      currentRoles: currentRoles.value
    })
    
    emit('confirm', {
      userId: props.user.id,
      roleIds: roleIds
    })
    
  } catch (error) {
    console.error('保存角色失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
}

const handleClosed = () => {
  currentRoles.value = []
  allRoles.value = []
}
</script>

<style scoped>
.role-assignment {
  max-height: 500px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  margin-bottom: 20px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.user-email {
  font-size: 14px;
  color: #6b7280;
}

.roles-content {
  min-height: 300px;
}

.current-roles {
  margin-bottom: 24px;
}

.current-roles h4,
.available-roles h4 {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-roles h4::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  border-radius: 2px;
}

.available-roles h4::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border-radius: 2px;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 40px;
  align-items: flex-start;
}

.role-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.role-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.role-item:hover {
  border-color: #4f46e5;
  box-shadow: 0 2px 8px rgba(79, 70, 229, 0.1);
  transform: translateY(-1px);
}

.role-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.role-info {
  flex: 1;
}

.role-name {
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 2px;
}

.role-desc {
  font-size: 12px;
  color: #6b7280;
}

.role-action {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.role-item:hover .role-action {
  opacity: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 滚动条样式 */
.role-list::-webkit-scrollbar {
  width: 6px;
}

.role-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.role-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.role-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 标签样式增强 */
:deep(.el-tag) {
  font-weight: 500;
  border-radius: 6px;
  padding: 8px 12px;
  margin: 2px;
}

:deep(.el-tag.el-tag--large) {
  height: auto;
  line-height: 1.2;
}

:deep(.el-tag__close) {
  margin-left: 8px;
}

/* 分割线样式 */
:deep(.el-divider) {
  margin: 20px 0;
}

:deep(.el-divider__text) {
  font-weight: 600;
  color: #374151;
}

/* 按钮样式 */
:deep(.el-button.is-circle) {
  width: 28px;
  height: 28px;
  padding: 0;
}

/* 空状态样式 */
.role-tags .el-tag:only-child {
  background: #f3f4f6;
  color: #6b7280;
  border: 1px dashed #d1d5db;
}
</style>
